/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.teach.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.ConstantEnum;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.ReturnObject;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.web.ExcelController;
import com.thinkgem.jeesite.modules.act.entity.Act;
import com.thinkgem.jeesite.modules.act.utils.ActUtils;
import com.thinkgem.jeesite.modules.sys.security.FormAuthenticationFilter;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.teach.entity.TpTeachAchievement;
import com.thinkgem.jeesite.modules.teach.entity.TpTeachArticles;
import com.thinkgem.jeesite.modules.teach.service.TpTeachArticlesService;

/**
 * 教学文章Controller
 * @author 康力
 * @version 2018-03-11
 */
@Controller
@RequestMapping(value = "${adminPath}/teach/tpTeachArticles")
public class TpTeachArticlesController extends ExcelController<TpTeachArticles> {

	@Autowired
	private TpTeachArticlesService tpTeachArticlesService;

	@Autowired
	private SystemService systemService;

	@ModelAttribute
	public TpTeachArticles get(@RequestParam(required=false) String id) {
		TpTeachArticles entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = tpTeachArticlesService.get(id);
		}
		if (entity == null){
			entity = new TpTeachArticles();
		}
		//根据拥有当前菜单角色的最大的数据范围 判断是否是获取本人数据
		entity.setUserDataScope(systemService.getCurUserDataScopeByPermission("teach:tpTeachArticles:view"));
		if (entity.getIsNewRecord() && entity.getUserDataScope() == 0) {// 个人数据权限，获取个人信息
			entity.setUser(UserUtils.getUser());// 设置人员
			if (entity.getUser() != null) {
				entity.setDepartment(entity.getUser().getOffice());// 设置科室
				if (entity.getDepartment() != null) {
					// 设置教研室
					entity.setTrc(systemService.findParentByOfficeId(entity.getDepartment().getId()));
				}
			}
		}
		return entity;
	}
	
	@RequiresPermissions("teach:tpTeachArticles:view")
	@RequestMapping(value = {"list", ""})
	public String list(TpTeachArticles tpTeachArticles, HttpServletRequest request, HttpServletResponse response, Model model) {
		String str = request.getRequestURI().replaceFirst(request.getContextPath()+Global.getConfig("adminPath"), "");
		model.addAttribute("remark",systemService.getRemark(str));
		//根据拥有当前菜单角色的最大的数据范围 判断是否是获取本人数据
		tpTeachArticles.setUserDataScope(systemService.getCurUserDataScopeByPermission("teach:tpTeachArticles:view"));
		if(tpTeachArticles.getUserDataScope() == 0){
			tpTeachArticles.setUser(UserUtils.getUser());
		}else{//获得当前登录人部门下的数据
			if(tpTeachArticles.getDepartment() == null)tpTeachArticles.setDepartment(UserUtils.getUser().getOffice());
		}
		model.addAttribute("isStudent", request.getParameter("isStudent"));
		Page<TpTeachArticles> page = tpTeachArticlesService.findPage(new Page<TpTeachArticles>(request, response), tpTeachArticles);
		if(WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM)){//移动端请求，封装数据
			ReturnObject rtobj = new ReturnObject();
			rtobj.setResult(ConstantEnum.success.getCode());
			rtobj.setMsg(ConstantEnum.success.getName());
			rtobj.setData(page);
			return renderString(response, rtobj);
		}
		model.addAttribute("page", page);
		return "modules/teach/tpTeachArticlesList";
	}

	@RequiresPermissions("teach:tpTeachArticles:view")
	@RequestMapping(value = "form")
	public String form(TpTeachArticles tpTeachArticles, Model model, HttpServletRequest request, HttpServletResponse response) {
		//如果为新增数据并且数据权限为个人数据的情况下，启动审批流程
		String viewName = "";
		if(tpTeachArticles == null ||
				(tpTeachArticles.getStatus()!= null && tpTeachArticles.getStatus() == 2)||
				(StringUtils.isBlank(tpTeachArticles.getId())&&StringUtils.isBlank(tpTeachArticles.getAct().getProcInsId()))){
			//根据流程名称获取最新的流程实例名称
			String procDefId = null;
			if(systemService.getCurUserDataScopeByPermission("teach:tpTeachArticles:view") == 0){
				if(tpTeachArticles.getIsStudent() == 1){//学员数据走学员审批流程
					procDefId =  systemService.getprocDefIdByProcDefKey(ActUtils.TP_TEACH_ARTICLES_STUDENT[0]);
				}else{
					procDefId =  systemService.getprocDefIdByProcDefKey(ActUtils.TP_TEACH_ARTICLES[0]);
				}
			}
			Act act = new Act();
			act.setProcDefId(procDefId);
			tpTeachArticles.setAct(act);
			viewName="tpTeachArticlesForm";
		} else if (tpTeachArticles.getAct() != null && tpTeachArticles.getAct().getTaskDefKey() != null
				&& tpTeachArticles.getAct().getTaskDefKey().startsWith("audit")
				&&tpTeachArticles.getAct().isTodoTask()) {
			viewName="tpTeachArticlesAudit";
		}else{
			viewName="tpTeachArticlesView";
			//如果实体类内容未查出，使用ProcInsId查询
			Act act = tpTeachArticles.getAct();
			if(StringUtils.isBlank(tpTeachArticles.getId()) && act != null
					&& StringUtils.isNotBlank(act.getProcInsId())){
				tpTeachArticles.setProcInsId(act.getProcInsId());
				List<TpTeachArticles> list = tpTeachArticlesService.findList(tpTeachArticles);
				if(list.size() == 1){
					tpTeachArticles = list.get(0);
					tpTeachArticles.setAct(act);
				}
			}
		}
		model.addAttribute("tpTeachArticles", tpTeachArticles);
		model.addAttribute("isStudent", request.getParameter("isStudent"));
		if(WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM)){//移动端请求，封装数据
			ReturnObject rtobj = new ReturnObject();
			rtobj.setResult(ConstantEnum.success.getCode());
			rtobj.setMsg(ConstantEnum.success.getName());
			ExportExcel ex = new ExportExcel("", TpTeachArticles.class);
			tpTeachArticles = ex.getMobileDataList(tpTeachArticles);
			tpTeachArticles.setPropertyNameMap(ex.getPropertyNameMap());
			rtobj.setData(tpTeachArticles);
			return renderString(response, rtobj);
		}
		return "modules/teach/"+viewName;
	}

	@RequiresPermissions("teach:tpTeachArticles:edit")
	@RequestMapping(value = "save")
	public String save(TpTeachArticles tpTeachArticles, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request, HttpServletResponse response) {
		if (!beanValidator(model, tpTeachArticles)){
			return form(tpTeachArticles, model,request,response);
		}
		tpTeachArticlesService.save(tpTeachArticles);
		addMessage(redirectAttributes, "保存教学文章成功");
		return "redirect:"+Global.getAdminPath()+"/teach/tpTeachArticles/list?isStudent="+request.getParameter("isStudent");
	}
	
	@RequiresPermissions("teach:tpTeachArticles:edit")
	@RequestMapping(value = "delete")
	public String delete(TpTeachArticles tpTeachArticles, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		tpTeachArticlesService.delete(tpTeachArticles);
		addMessage(redirectAttributes, "删除教学文章成功");
		return "redirect:"+Global.getAdminPath()+"/teach/tpTeachArticles/list?isStudent="+request.getParameter("isStudent");
	}

	@Override
	protected TpTeachArticlesService getService() {
		return tpTeachArticlesService;
	}
	@Override
	public String getTitle() {
		return "发表文章";
	}

	@Override
	public String defaultStr() {
		return "/teach/tpTeachArticles/?repage";
	}

	@Override
	public CrudService baseService() {
		return tpTeachArticlesService;
	}

	@Override
	@RequiresPermissions("teach:tpTeachArticles:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes,TpTeachArticles t) {
		return super.importFileTemplate(response,redirectAttributes,t);
	}

	@RequiresPermissions("teach:tpTeachArticles:edit")
	@RequestMapping(value = "import", method= RequestMethod.POST)
	public String importFileNew(MultipartFile file, RedirectAttributes redirectAttributes,TpTeachArticles data, HttpServletRequest request) {
		importFile(file,redirectAttributes,data);
		return "redirect:"+Global.getAdminPath()+"/teach/tpTeachArticles/list?isStudent="+request.getParameter("isStudent");
	}

	@Override
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes,TpTeachArticles data) {
		return super.importFile(file,redirectAttributes,data);
	}

	@Override
	@RequiresPermissions("teach:tpTeachArticles:view")
	@RequestMapping(value = "export", method=RequestMethod.POST)
	public String exportFile(TpTeachArticles t, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		if(t.getIsStudent()!= null && t.getIsStudent() == 1){
			return super.exportFile(t,3,request,response,redirectAttributes);
		}else{
			return super.exportFile(t,request,response,redirectAttributes);
		}
	}
	
}